﻿Imports System.Net

Public Class frm_main
    Dim URL As String = "http://localhost/download/file.mkv"
    Dim OUTPUT As String = My.Application.Info.DirectoryPath & "\tmp"

    Delegate Sub ChangeTextsSafe(ByVal length As Long, ByVal position As Integer, ByVal percent As Integer, ByVal speed As Double)
    Delegate Sub DownloadCompleteSafe(ByVal cancelled As Boolean)

    Public Sub DownloadComplete(ByVal cancelled As Boolean)
        If cancelled Then
            Me.lblstat.Text = "Status : " & "Cancelled"
        Else
            Me.lblstat.Text = "Status : " & "Successfully downloaded"
        End If

        'Me.ProgressBar1.Value = 0
    End Sub

    Public Sub ChangeTexts(ByVal length As Long, ByVal position As Integer, ByVal percent As Integer, ByVal speed As Double)
        Me.lblstat.Text = "Status : " & Math.Round((position / 1024), 2) & " KB of " & Math.Round((length / 1024), 2) & "KB (" & Me.ProgressBar1.Value & "%)"
        Me.lblpercent.Text = Me.ProgressBar1.Value & "%"
        If speed = -1 Then
            Me.lblspd.Text = "Speed : " & "calculating..."
        Else
            Me.lblspd.Text = "Speed : " & Math.Round((speed / 1024), 2) & " KB/s"
        End If

        Me.ProgressBar1.Value = percent
    End Sub


    Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        Dim theResponse As HttpWebResponse
        Dim theRequest As HttpWebRequest

        Try
            theRequest = WebRequest.Create(URL)
            theResponse = theRequest.GetResponse
        Catch ex As Exception
            MessageBox.Show("An error occurred while downloading file. Possibe causes:" & ControlChars.CrLf & _
                            "1) File doesn't exist" & ControlChars.CrLf & _
                            "2) Remote server error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Dim cancelDelegate As New DownloadCompleteSafe(AddressOf DownloadComplete)
            Me.Invoke(cancelDelegate, True)
            Exit Sub
        End Try

        Dim length As Long = theResponse.ContentLength
        Dim safedelegate As New ChangeTextsSafe(AddressOf ChangeTexts)
        Me.Invoke(safedelegate, length, 0, 0, 0)
        Dim writeStream As New IO.FileStream(OUTPUT, IO.FileMode.Create)
        Dim nRead As Integer
        Dim speedtimer As New Stopwatch
        Dim currentspeed As Double = -1
        Dim readings As Integer = 0

        Do
            If BackgroundWorker1.CancellationPending Then
                Exit Do
            End If
            speedtimer.Start()
            Dim readBytes(4095) As Byte
            Dim bytesread As Integer = theResponse.GetResponseStream.Read(readBytes, 0, 4096)
            nRead += bytesread
            Dim percent As Short = (nRead / length) * 100
            Me.Invoke(safedelegate, length, nRead, percent, currentspeed)

            If bytesread = 0 Then Exit Do
            writeStream.Write(readBytes, 0, bytesread)
            speedtimer.Stop()
            readings += 1

            If readings >= 5 Then
                currentspeed = 20480 / (speedtimer.ElapsedMilliseconds / 1000)
                speedtimer.Reset()
                readings = 0
            End If
        Loop

        theResponse.GetResponseStream.Close()
        writeStream.Close()

        If Me.BackgroundWorker1.CancellationPending Then
            IO.File.Delete(output)
            Dim cancelDelegate As New DownloadCompleteSafe(AddressOf DownloadComplete)
            Me.Invoke(cancelDelegate, True)
            Exit Sub
        End If

        Dim completeDelegate As New DownloadCompleteSafe(AddressOf DownloadComplete)
        Me.Invoke(completeDelegate, False)
    End Sub


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Me.BackgroundWorker1.RunWorkerAsync()
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Try
            BackgroundWorker1.CancelAsync()
        Catch ex As Exception

        End Try
    End Sub

    Private Sub frm_main_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        End
    End Sub

    Private Sub frm_main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        '# Parsing Command Line Argument
        '--------------------------------
        Dim cli_Arg() As String = System.Environment.GetCommandLineArgs
        Dim tmp_arg() As String
        'Dim i As Integer = 0
        'For i = 1 To cli_Arg.Length - 1
        '    MsgBox(cli_Arg(i))
        'Next
        tmp_arg = cli_Arg(1).Split(";")
        '--------------------------------

        '# init url file dan output file
        '--------------------------------
        ' cek tmp directory
        If My.Computer.FileSystem.DirectoryExists(OUTPUT & "\") = False Then
            My.Computer.FileSystem.CreateDirectory(OUTPUT & "\")
        End If
        ' init url
        URL = tmp_arg(1)
        ' init output
        OUTPUT &= "\ppob.zip"

        lblversion.Text = tmp_arg(0)

        ' run update
        Me.BackgroundWorker1.RunWorkerAsync()

    End Sub

    Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
        Try
            ZipExtract.Extract(OUTPUT, My.Application.Info.DirectoryPath & "\", True)
            MsgBox("Program berhasil diupdate.", MsgBoxStyle.OkOnly, "Update Program")
            End
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally

        End Try
    End Sub
End Class